const GasStation = require('../models/GasStation');
const { validationResult } = require('express-validator');

// Get all gas stations with filtering and pagination
exports.getAllGasStations = async (req, res) => {
  try {
    const { page = 1, pageSize = 10, keyword = '', filter = 'all', sort = 'distance', asc = 0 } = req.query;
    
    // If filter is 'nearby', we need user's location
    if (filter === 'nearby') {
      const { latitude, longitude } = req.query;
      
      if (!latitude || !longitude) {
        return res.status(400).json({ message: '需要位置信息来查找附近加油站' });
      }
      
      const nearbyStations = await GasStation.getNearby(
        parseFloat(latitude), 
        parseFloat(longitude),
        5000, // 5km radius
        parseInt(pageSize)
      );
      
      return res.json({
        list: nearbyStations,
        pagination: {
          total: nearbyStations.length,
          page: parseInt(page),
          pageSize: parseInt(pageSize)
        }
      });
    }
    
    // Normal filtered query
    const result = await GasStation.getAll({ 
      page: parseInt(page), 
      pageSize: parseInt(pageSize), 
      keyword, 
      filter, 
      sort, 
      asc: parseInt(asc) 
    });
    
    res.json(result);
  } catch (error) {
    console.error('Error getting gas stations:', error);
    res.status(500).json({ message: '获取加油站列表失败' });
  }
};

// Get gas station by ID
exports.getGasStationById = async (req, res) => {
  try {
    const { id } = req.params;
    const station = await GasStation.getById(id);
    
    if (!station) {
      return res.status(404).json({ message: '加油站不存在' });
    }
    
    res.json(station);
  } catch (error) {
    console.error('Error getting gas station details:', error);
    res.status(500).json({ message: '获取加油站详情失败' });
  }
};

// Create new gas station (admin only)
exports.createGasStation = async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
    
    const { name, address, price, latitude, longitude, rating } = req.body;
    
    const stationId = await GasStation.create({
      name,
      address,
      price,
      latitude,
      longitude,
      rating
    });
    
    res.status(201).json({ 
      message: '加油站创建成功', 
      stationId 
    });
  } catch (error) {
    console.error('Error creating gas station:', error);
    res.status(500).json({ message: '创建加油站失败' });
  }
};

// Update gas station (admin only)
exports.updateGasStation = async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
    
    const { id } = req.params;
    const { name, address, price, latitude, longitude, rating } = req.body;
    
    const success = await GasStation.update(id, {
      name,
      address,
      price,
      latitude,
      longitude,
      rating
    });
    
    if (!success) {
      return res.status(404).json({ message: '加油站不存在' });
    }
    
    res.json({ message: '加油站更新成功' });
  } catch (error) {
    console.error('Error updating gas station:', error);
    res.status(500).json({ message: '更新加油站失败' });
  }
};

// Delete gas station (admin only)
exports.deleteGasStation = async (req, res) => {
  try {
    const { id } = req.params;
    
    const success = await GasStation.delete(id);
    
    if (!success) {
      return res.status(404).json({ message: '加油站不存在' });
    }
    
    res.json({ message: '加油站删除成功' });
  } catch (error) {
    console.error('Error deleting gas station:', error);
    res.status(500).json({ message: '删除加油站失败' });
  }
};

// Record a gas transaction
exports.recordGasTransaction = async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
    
    const userId = req.user.id;
    const { stationId, amount } = req.body;
    
    // Check if user has enough balance
    const balance = await GasStation.getUserGasCardBalance(userId);
    
    if (balance < amount) {
      return res.status(400).json({ message: '加油卡余额不足' });
    }
    
    // Record transaction
    const transactionId = await GasStation.recordTransaction(userId, stationId, amount);
    
    // Update user balance
    await GasStation.updateUserGasCardBalance(userId, -amount);
    
    res.status(201).json({
      message: '支付成功',
      transactionId,
      newBalance: balance - amount
    });
  } catch (error) {
    console.error('Error recording gas transaction:', error);
    res.status(500).json({ message: '支付失败' });
  }
};

// Recharge gas card
exports.rechargeGasCard = async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
    
    const userId = req.user.id;
    const { amount } = req.body;
    
    if (amount <= 0) {
      return res.status(400).json({ message: '充值金额必须大于0' });
    }
    
    // Update user balance
    await GasStation.updateUserGasCardBalance(userId, amount);
    
    // Get new balance
    const newBalance = await GasStation.getUserGasCardBalance(userId);
    
    res.json({
      message: '充值成功',
      newBalance
    });
  } catch (error) {
    console.error('Error recharging gas card:', error);
    res.status(500).json({ message: '充值失败' });
  }
};

// Get user's gas card balance
exports.getGasCardBalance = async (req, res) => {
  try {
    const userId = req.user.id;
    
    const balance = await GasStation.getUserGasCardBalance(userId);
    
    res.json({ balance });
  } catch (error) {
    console.error('Error getting gas card balance:', error);
    res.status(500).json({ message: '获取加油卡余额失败' });
  }
}; 